<template>
  <div class="UploadImg ">
    <el-upload
      :class="{avatar:fileList.length>0}"
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>

    <!-- 进度条 -->
    <el-progress v-if="percenShow" :percentage="percen" :show-text="false" style="width:148px" />

    <!-- 预览模态框 -->
    <el-dialog title="预览" :visible="previewShow" @close="previewShow=false">
      <el-row type="flex" justify="center">
        <img :src="imgSrc" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID96nEPJwINBizyh9gwwf7ICqDKAj13nGS',
  SecretKey: 'xe4D5i6D3dw4vVoqc7LJ0QZR3OSFkzyg'
})
export default {
  data() {
    return {
      fileList: [
        // { url: 'https://img0.baidu.com/it/u=1443138647,880212012&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=571' }
      ],
      //   预览
      previewShow: false,
      imgSrc: '',
      //   百分比
      percen: 0,
      percenShow: false
    }
  },
  methods: {
    //   预览
    onPreview(file) {
      this.previewShow = true
      this.imgSrc = file.url
      console.log(file)
    },
    // 移出图片
    onRemove(file, fileList) {
      //   等于一个新的数组避免内存相同出bug
      this.fileList = [...fileList]
    },
    // 图片改变
    onChange(file, fileList) {
      this.fileList = [...fileList]
    },
    // 上传 覆盖原本的上传行为
    upload(data) {
      this.percenShow = true
      console.log(data)
      cos.putObject({
        Bucket: 'heima-renzi-1307117927', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: data.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percen = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        this.fileList[0].url = 'http://' + data.Location
        this.fileList[0].status = 'success'
        this.percenShow = false
      })
    },
    // 上传之前
    beforeUpload(file) {
    //   console.log(file)
      const size = 200 * 1024 // 2Kb
      if (file.size > size) {
        this.$message.warning('请控制大小在200Kb内')
        return false
      }
      const white = ['image/jpeg', 'image/png']
      if (white.indexOf(file.type) === -1) {
        this.$message.warning('文件类型要为image或png')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar{
    ::v-deep .el-upload--picture-card{
        display: none;
    }
}
</style>
